/*
 * CurveDialog.java
 *
 * Created on Sep 23, 2011, 11:59:10 AM
 */
package com.photoexpert;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.ByteLookupTable;
import java.awt.image.LookupOp;
import javax.swing.JDialog;
import javax.swing.JPanel;

/**
 *
 * @author PANYIXIN
 */
class CurveDialog extends JDialog {

    private enum MOVING_POINTS {
        NONE,
        POINT1,
        POINT2
    }

    /** Creates new form LevelDialog */
    CurveDialog() {
        super(App.Instance(), true);
        initComponents();
        setLocation(200, 200);
        _curve.addMouseListener((CurvePanel)_curve);
        _curve.addMouseMotionListener((CurvePanel)_curve);
        setVisible(true);
    }

    private class CurvePanel extends JPanel implements MouseListener, MouseMotionListener {

        private CurvePanel() { }

        @Override
        public void paint(Graphics g) {
            g.setColor(Color.WHITE);
            Rectangle r = getVisibleRect();
            g.fillRect(0, 0, r.width, r.height);
            g.setColor(Color.LIGHT_GRAY);
            g.drawLine(0, 255, 255, 0);
            g.drawLine(0, 128, 255, 128);
            g.drawLine(128, 0, 128, 255);
            g.setColor(Color.BLACK);
            int x = 0;
            int y = 0;
            if(_x1 > 0)
                g.drawRect(_x1 - 1, 256 - _y1 - 1, 2, 2);
            if(_x2 > 0)
                g.drawRect(_x2 - 1, 256 - _y2 - 1, 2, 2);
            for(int i = 0; i < 256; ++i) {
                g.drawLine(x, 256 - y, i, 256 - _data[i]);
                x = i;
                y = _data[i];
            }
        }

        private void multiply(double d[], double ratio) {
            for(int i = 0; i < d.length; ++i)
                d[i] *= ratio;
        }

        private void plus(double d1[], double d2[]) {
            for(int i = 0; i < d1.length; ++i)
                d1[i] += d2[i];
        }

        private void calculateCurve() {
            if(_x2 > 0) {
                // both 2 points are set, calculate as 3rd degree curve
                double x1 = _x1 * 1d / 256;
                double y1 = _y1 * 1d / 256;
                double x2 = _x2 * 1d / 256;
                double y2 = _y2 * 1d / 256;
                double m1 = 0d - sqrt2d2 + sqrt2 * x1 + sqrt2d2 * (y1 - x1);
                double n1 = sqrt2d2 * (y1 - x1);
                double m2 = 0d - sqrt2d2 + sqrt2 * x2 + sqrt2d2 * (y2 - x2);
                double n2 = sqrt2d2 * (y2 - x2);
                double e[] = new double[] {
                    -sqrt2 / 4, 0.5, -sqrt2d2, 1, 0,
                    sqrt2 / 4, 0.5, sqrt2d2, 1, 0,
                    m1 * m1 * m1, m1 * m1, m1, 1, n1,
                    m2 * m2 * m2, m2 * m2, m2, 1, n2
                };
                double x[][] = new double[4][5];
                for(int i = 0; i < 4; ++i)
                    for(int j = 0; j < 5; ++j) {
                        double ddd = e[i * 5 + j];
                        x[i][j] = ddd;
                    }
                if(x[0][1] != 0) {
                    multiply(x[1], 0d - x[0][1] / x[1][1]);
                    plus(x[0], x[1]);
                }
                if(x[2][1] != 0) {
                    multiply(x[1], 0d - x[2][1] / x[1][1]);
                    plus(x[2], x[1]);
                }
                if(x[3][1] != 0) {
                    multiply(x[1], 0d - x[3][1] / x[1][1]);
                    plus(x[3], x[1]);
                }
                if(x[0][2] != 0) {
                    multiply(x[2], 0d - x[0][2] / x[2][2]);
                    plus(x[0], x[2]);
                }
                if(x[3][2] != 0) {
                    multiply(x[2], 0d - x[3][2] / x[2][2]);
                    plus(x[3], x[2]);
                }
                if(x[0][3] != 0) {
                    multiply(x[3], 0d - x[0][3] / x[3][3]);
                    plus(x[0], x[3]);
                }
                double a = x[0][4] / x[0][0];
                if(x[3][0] != 0) {
                    multiply(x[0], 0d - x[3][0] / x[0][0]);
                    plus(x[3], x[0]);
                }
                double d = x[3][4] / x[3][3];
                if(x[2][0] != 0) {
                    multiply(x[0], 0d - x[2][0] / x[0][0]);
                    plus(x[2], x[0]);
                }
                if(x[2][3] != 0) {
                    multiply(x[3], 0d - x[2][3] / x[3][3]);
                    plus(x[2], x[3]);
                }
                double c = x[2][4] / x[2][2];
                if(x[1][0] != 0) {
                    multiply(x[0], 0d - x[1][0] / x[0][0]);
                    plus(x[1], x[0]);
                }
                if(x[1][3] != 0) {
                    multiply(x[3], 0d - x[1][3] / x[3][3]);
                    plus(x[1], x[3]);
                }
                if(x[1][2] != 0) {
                    multiply(x[2], 0d - x[1][2] / x[2][2]);
                    plus(x[1], x[2]);
                }
                double b = x[1][4] / x[1][1];
                double m3 = -sqrt2d2;
                double step = 1d / 512;
                while(m3 <= sqrt2d2) {
                    double n3 = a * m3 * m3 * m3 + b * m3 * m3 + c * m3 + d;
                    double x3 = ((sqrt2d2 + m3 - n3) * sqrt2d2) * 256;
                    double y3 = ((sqrt2d2 + m3 + n3) * sqrt2d2) * 256;
                    if(x3 >= 0 && x3 <= 255)
                        _data[(int)x3] = (int)y3;
                    m3 += step;
                }
            } else if(_x1 > 0) {
                // only 1 point is set, calculate as 2nd degree curve
                double x = _x1 * 1d / 256;
                double y = _y1 * 1d / 256;
                double m = 0d - sqrt2d2 + sqrt2 * x + sqrt2d2 * (y - x);
                double n = sqrt2d2 * (y - x);
                double a = n * 2 / (m * m * 2 - 1);
                double c =  a * (-0.5);
                double m1 = -sqrt2d2;
                double step = 1d / 512;
                while(m1 <= sqrt2d2) {
                    double n1 = a * m1 * m1 + c;
                    double x1 = ((sqrt2d2 + m1 - n1) * sqrt2d2) * 256;
                    double y1 = ((sqrt2d2 + m1 + n1) * sqrt2d2) * 256;
                    _data[(int)x1] = (int)y1;
                    m1 += step;
                }
            }
            repaint();
            preview();
        }

        @Override
        public void mouseClicked(MouseEvent e) {
            if(_x1 < 0) {
                _x1 = e.getX();
                _y1 = 256 - e.getY();
                calculateCurve();
            } else if(_x2 < 0) {
                _x2 = e.getX();
                _y2 = 256 - e.getY();
                calculateCurve();
            }
        }

        @Override
        public void mousePressed(MouseEvent e) { }
        @Override
        public void mouseReleased(MouseEvent e) { }
        @Override
        public void mouseEntered(MouseEvent e) { }
        @Override
        public void mouseExited(MouseEvent e) { }

        @Override
        public void mouseDragged(MouseEvent e) {
            switch(_movingPoint) {
                case POINT1 :
                    _x1 = e.getX();
                    _y1 = 256 - e.getY();
                    calculateCurve();
                    break;
                case POINT2 :
                    _x2 = e.getX();
                    _y2 = 256 - e.getY();
                    calculateCurve();
                    break;
            }
        }

        @Override
        public void mouseMoved(MouseEvent e) {
            int x = e.getX();
            int y = 256 - e.getY();
            if(_x2 > 0 && Math.abs(x - _x2) < 3 && Math.abs(y - _y2) < 3) {
                _movingPoint = MOVING_POINTS.POINT2;
                setCursor(Cursors._moveCursor);
            } else if(_x1 > 0 && Math.abs(x - _x1) < 3 && Math.abs(y - _y1) < 3) {
                _movingPoint = MOVING_POINTS.POINT1;
                setCursor(Cursors._moveCursor);
            } else {
                _movingPoint = MOVING_POINTS.NONE;
                setCursor(Cursors._defaultCursor);
            }
        }

        private MOVING_POINTS   _movingPoint = MOVING_POINTS.NONE;
        private int             _x1 = -1;
        private int             _y1 = -1;
        private int             _x2 = -1;
        private int             _y2 = -1;
        private int[]           _data = new int[256];

    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        _curve = new CurveDialog.CurvePanel();
        _previewLabel = new javax.swing.JLabel();
        _previewPane = PreviewPane.CreateInstance();
        _cancel = new javax.swing.JButton();
        _ok = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Curve");
        setModal(true);
        setResizable(false);

        _curve.setPreferredSize(new java.awt.Dimension(256, 256));

        javax.swing.GroupLayout _curveLayout = new javax.swing.GroupLayout(_curve);
        _curve.setLayout(_curveLayout);
        _curveLayout.setHorizontalGroup(
            _curveLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 260, Short.MAX_VALUE)
        );
        _curveLayout.setVerticalGroup(
            _curveLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 256, Short.MAX_VALUE)
        );

        _previewLabel.setText("Preview:");

        _previewPane.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        _previewPane.setPreferredSize(new java.awt.Dimension(252, 192));

        javax.swing.GroupLayout _previewPaneLayout = new javax.swing.GroupLayout(_previewPane);
        _previewPane.setLayout(_previewPaneLayout);
        _previewPaneLayout.setHorizontalGroup(
            _previewPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 248, Short.MAX_VALUE)
        );
        _previewPaneLayout.setVerticalGroup(
            _previewPaneLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 190, Short.MAX_VALUE)
        );

        _cancel.setText("Cancel");
        _cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                _cancelActionPerformed(evt);
            }
        });

        _ok.setText("OK");
        _ok.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                _okActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(_curve, javax.swing.GroupLayout.DEFAULT_SIZE, 260, Short.MAX_VALUE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(_previewLabel)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(_ok, javax.swing.GroupLayout.PREFERRED_SIZE, 67, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(18, 18, 18)
                            .addComponent(_cancel))
                        .addComponent(_previewPane, javax.swing.GroupLayout.PREFERRED_SIZE, 250, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(_previewLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(_previewPane, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 24, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(_cancel)
                            .addComponent(_ok)))
                    .addComponent(_curve, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void _cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__cancelActionPerformed
        setVisible(false);
        dispose();
    }//GEN-LAST:event__cancelActionPerformed

    private void _okActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event__okActionPerformed
        if(_op != null)
            Implementor.Instance().adjust(_op);
        setVisible(false);
        dispose();
    }//GEN-LAST:event__okActionPerformed

    private void preview() {
        for (int j=0; j<256; j++) {
            int v = ((CurvePanel)_curve)._data[j];
            byte b = 0;
            if(v > 255)
                b = (byte)255;
            else if(v > 0)
                b = (byte)v;
            _byteTable[j] = b;
        }
        _lookupTable = new ByteLookupTable(0, _byteTable);
        _op = new LookupOp(_lookupTable, null);
        ((PreviewPane)_previewPane).setOp(_op);
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton _cancel;
    private javax.swing.JPanel _curve;
    private javax.swing.JButton _ok;
    private javax.swing.JLabel _previewLabel;
    private javax.swing.JPanel _previewPane;
    // End of variables declaration//GEN-END:variables
    private byte[]              _byteTable = new byte[256];
    private ByteLookupTable     _lookupTable = null;
    private LookupOp            _op = null;
    private static final double sqrt2 = Math.sqrt(2);
    private static final double sqrt2d2 = sqrt2 / 2;
}
